
#import "WKWebViewController.h"
#import <WebKit/WebKit.h>

@interface WKWebViewController () <WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSString *urlString;

@end

@implementation WKWebViewController


- (instancetype)initWithUrlSting:(NSString *)urlSting {
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        self.urlString = urlSting;
    }
    return self;
}

- (void)loadView {
    
    // 图片原始比例，可缩放
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    
    // 图片屏幕比例，不可缩放
//    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, initial-scale=1.0, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
    
    WKWebViewConfiguration *webConfiguration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    webConfiguration.userContentController = wkUController;
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [wkUController addUserScript:wkUserScript];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfiguration];
    self.webView.UIDelegate = self;
    self.view = self.webView;
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!kIsEmpty(self.urlString)) {
        DEBUGLOG(@"%@", self.urlString);
        NSURL *url = [NSURL URLWithString:self.urlString];
        NSURLRequest *myRequest = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:myRequest];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"title"]) {
        self.navigationItem.title = self.webView.title;
    }
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"title" context:nil];
}

#pragma mark ------- Lazy Methods -------

- (void)masonryLayout {
    
}

@end
